package com.mrd.spring.config;

import java.util.Arrays;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.alibaba.druid.pool.xa.DruidXADataSource;
import com.atomikos.jdbc.AtomikosDataSourceBean;
import com.github.pagehelper.PageHelper;

@Configuration
// 扫描 Mapper 接口并容器管理
@EnableTransactionManagement
@MapperScan(basePackages = MyBatisDataSourceConfig.PACKAGE,
    sqlSessionFactoryRef = "sqlSessionFactory")
public class MyBatisDataSourceConfig {
  @Autowired
  private Environment environment;
  @Autowired
  DataSourcePropertis dataSourcePropertis;

  @ConditionalOnClass(DataSourcePropertis.class)
  @Bean(name = "myBatisDataSource")
  public AtomikosDataSourceBean myBatisDataSource() {
    AtomikosDataSourceBean ds = new AtomikosDataSourceBean();
    ds.setXaDataSourceClassName("com.alibaba.druid.pool.xa.DruidXADataSource");
    DruidXADataSource dataSource = new DruidXADataSource();
    dataSource.setUrl(dataSourcePropertis.getUrl());
    dataSource.setUsername(dataSourcePropertis.getUsername());
    dataSource.setPassword(dataSourcePropertis.getPassword());
    dataSource.setDriverClassName(dataSourcePropertis.getDriverClassName());
    dataSource.setInitialSize(dataSourcePropertis.getInitialSize());
    dataSource.setMinIdle(dataSourcePropertis.getMinIdle());
    dataSource.setMaxActive(dataSourcePropertis.getMaxActive());
    dataSource
        .setTimeBetweenEvictionRunsMillis(dataSourcePropertis.getMinEvictableIdleTimeMillis());
    dataSource.setMinEvictableIdleTimeMillis(dataSourcePropertis.getMinEvictableIdleTimeMillis());
    dataSource.setTestWhileIdle(true);// 在获取连接后，确定是否要进行连接空间时间的检查
    dataSource.setTestOnBorrow(true);// 获取连接检测
    dataSource.setTestOnReturn(false);// 获取连接检测
    dataSource.setValidationQuery("SELECT 'x' from dual");// 检测语句
    ds.setUniqueResourceName("mybatisDataSource");
    ds.setPoolSize(dataSourcePropertis.getInitialSize());
    ds.setXaDataSource(dataSource);
    ds.setMaxPoolSize(dataSourcePropertis.getMaxActive());
    ds.setXaDataSourceClassName("oracle.jdbc.xa.client.OracleXADataSource");

    System.err.println("#######################使用配置文件：" + Arrays.toString(environment.getActiveProfiles()) + " #######################");
    return ds;
  }

  // 精确到 master 目录，以便跟其他数据源隔离
  static final String PACKAGE = "com.mrd.gtimpframe.**.repository";
  static final String MAPPER_LOCATION = "classpath:com.mrd.gtimpframe.**.*.xml";
  private static String MYBATIS_CONFIG = "mybatis.xml";

  @Bean(name = "sqlSessionFactory")
  public SqlSessionFactory myBatisSqlSessionFactory(
      @Qualifier("myBatisDataSource") DataSource mybatisDataSource) throws Exception {
    final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
    sessionFactory.setDataSource(mybatisDataSource);
    // sessionFactory.setVfs(SpringBootVFS.class);
    sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
        .getResources(MyBatisDataSourceConfig.MAPPER_LOCATION));
    sessionFactory.setConfigLocation(new ClassPathResource(MYBATIS_CONFIG));

    // 分页插件
    PageHelper pageHelper = new PageHelper();
    Properties props = new Properties();
    props.setProperty("reasonable", "true");
    props.setProperty("supportMethodsArguments", "true");
    props.setProperty("returnPageInfo", "check");
    props.setProperty("params", "count=countSql");
    pageHelper.setProperties(props);
    // 添加插件
    sessionFactory.setPlugins(new Interceptor[] {pageHelper});
    return sessionFactory.getObject();
  }

  @Bean(name = "sqlSessionTemplate")
  @Primary
  public SqlSessionTemplate sqlSessionTemplate(
      @Qualifier("sqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
    return new SqlSessionTemplate(sqlSessionFactory);
  }

  // @Bean(name = "mybatisTransactionManager")
  //// @Primary
  // public DataSourceTransactionManager mybatisTransactionManager() {
  // return new DataSourceTransactionManager(dataSource());
  // }
}
